<template>
  <div class="app-container">
    <el-card class="search-wrapper">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item>
          <el-input
            v-model="queryParams.keyword"
            placeholder="管家姓名/手机号/工号"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.business_id" placeholder="所属商家" clearable>
            <el-option
              v-for="item in options.business"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.service_type" placeholder="服务分类" clearable>
            <el-option
              v-for="(label, value) in options.types"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.assign_status" placeholder="分配状态" clearable>
            <el-option
              v-for="(label, value) in options.assignStatus"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="success" @click="handleAdd">新增分配</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-wrapper">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
      >
        <el-table-column prop="service_name" label="管家姓名" width="120" />
        <el-table-column prop="service_no" label="平台工号" width="120" />
        <el-table-column prop="service_type_text" label="服务分类" width="120" />
        <el-table-column prop="business_name" label="所属商家" min-width="180" show-overflow-tooltip />
        <el-table-column prop="assign_date" label="分配日期" width="120" />
        <el-table-column prop="work_time" label="工作时间" width="180" show-overflow-tooltip />
        <el-table-column prop="assign_status" label="分配状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.assign_status === 1 ? 'success' : scope.row.assign_status === 2 ? 'warning' : 'info'">
              {{ scope.row.assign_status_text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="primary"
              link
              @click="handleDetail(scope.row)"
            >
              详情
            </el-button>
            <el-button
              v-if="scope.row.assign_status === 1"
              type="danger"
              link
              @click="handleCancel(scope.row)"
            >
              取消分配
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增分配' : '编辑分配'"
      v-model="dialogVisible"
      width="700px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="选择管家" prop="service_id">
          <el-select
            v-model="form.service_id"
            placeholder="请选择服务管家"
            filterable
            remote
            :remote-method="remoteSearchService"
            :loading="serviceLoading"
          >
            <el-option
              v-for="item in serviceOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <span>{{ item.name }}</span>
              <span class="option-info">{{ item.service_no }} | {{ item.service_type_text }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属商家" prop="business_id">
          <el-select v-model="form.business_id" placeholder="请选择所属商家">
            <el-option
              v-for="item in options.business"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分配日期" prop="assign_date">
          <el-date-picker
            v-model="form.assign_date"
            type="date"
            placeholder="请选择分配日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="工作时间" prop="work_time">
          <el-time-select
            v-model="form.work_start"
            placeholder="开始时间"
            :start="'06:00'"
            :step="'00:30'"
            :end="'22:00'"
          />
          <span class="mx-2">至</span>
          <el-time-select
            v-model="form.work_end"
            placeholder="结束时间"
            :start="'06:00'"
            :step="'00:30'"
            :end="'22:00'"
            :min-time="form.work_start"
          />
        </el-form-item>
        <el-form-item label="分配状态" prop="assign_status">
          <el-radio-group v-model="form.assign_status">
            <el-radio
              v-for="(label, value) in options.assignStatus"
              :key="value"
              :label="Number(value)"
            >{{ label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog
      title="分配详情"
      v-model="detailVisible"
      width="700px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="管家姓名">{{ detail.service_name }}</el-descriptions-item>
        <el-descriptions-item label="平台工号">{{ detail.service_no }}</el-descriptions-item>
        <el-descriptions-item label="服务分类">{{ detail.service_type_text }}</el-descriptions-item>
        <el-descriptions-item label="所属商家">{{ detail.business_name }}</el-descriptions-item>
        <el-descriptions-item label="分配日期">{{ detail.assign_date }}</el-descriptions-item>
        <el-descriptions-item label="工作时间">{{ detail.work_time }}</el-descriptions-item>
        <el-descriptions-item label="分配状态">
          <el-tag :type="detail.assign_status === 1 ? 'success' : detail.assign_status === 2 ? 'warning' : 'info'">
            {{ detail.assign_status_text }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detail.remark || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detail.created_at }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detail.updated_at }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 10,
  keyword: '',
  business_id: '',
  service_type: '',
  assign_status: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)

// 选项数据
const options = reactive({
  types: {
    1: '导游服务',
    2: '讲解服务',
    3: '接待服务',
    4: '咨询服务',
    5: '其他服务'
  },
  assignStatus: {
    1: '已分配',
    2: '待分配',
    0: '已取消'
  },
  business: []
})

// 获取选项数据
const getOptions = async () => {
  try {
    const res = await request.get('/app/ky_black/admin/service/assign/options')
    options.business = res.data.business || []
  } catch (error) {
    console.error('获取选项数据失败：', error)
  }
}

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    const res = await request.get('/app/ky_black/admin/service/assign/list', {
      params: queryParams
    })
    tableData.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取列表失败：', error)
  }
  loading.value = false
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  getList()
}

// 重置搜索
const resetQuery = () => {
  queryParams.keyword = ''
  queryParams.business_id = ''
  queryParams.service_type = ''
  queryParams.assign_status = ''
  handleSearch()
}

// 分页
const handleSizeChange = (val) => {
  queryParams.limit = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.page = val
  getList()
}

// 弹窗相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)

// 表单数据
const form = reactive({
  service_id: '',
  business_id: '',
  assign_date: '',
  work_start: '',
  work_end: '',
  assign_status: 1,
  remark: ''
})

// 计算工作时间
const workTime = computed(() => {
  if (form.work_start && form.work_end) {
    return `${form.work_start}-${form.work_end}`
  }
  return ''
})

// 表单校验规则
const rules = {
  service_id: [
    { required: true, message: '请选择服务管家', trigger: 'change' }
  ],
  business_id: [
    { required: true, message: '请选择所属商家', trigger: 'change' }
  ],
  assign_date: [
    { required: true, message: '请选择分配日期', trigger: 'change' }
  ],
  work_start: [
    { required: true, message: '请选择工作开始时间', trigger: 'change' }
  ],
  work_end: [
    { required: true, message: '请选择工作结束时间', trigger: 'change' }
  ]
}

// 远程搜索服务管家
const serviceLoading = ref(false)
const serviceOptions = ref([])

const remoteSearchService = async (query) => {
  if (query) {
    serviceLoading.value = true
    try {
      const res = await request.get('/app/ky_black/admin/service/search', {
        params: { keyword: query }
      })
      serviceOptions.value = res.data || []
    } catch (error) {
      console.error('搜索服务管家失败：', error)
    }
    serviceLoading.value = false
  } else {
    serviceOptions.value = []
  }
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  Object.keys(form).forEach(key => {
    form[key] = key === 'assign_status' ? 1 : ''
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row) => {
  dialogType.value = 'edit'
  try {
    const res = await request.get(`/app/ky_black/admin/service/assign/${row.id}`)
    const data = res.data
    Object.assign(form, {
      ...data,
      work_start: data.work_time?.split('-')[0],
      work_end: data.work_time?.split('-')[1]
    })
    dialogVisible.value = true
  } catch (error) {
    console.error('获取详情失败：', error)
  }
}

// 详情
const detailVisible = ref(false)
const detail = ref({})

const handleDetail = async (row) => {
  try {
    const res = await request.get(`/app/ky_black/admin/service/assign/${row.id}`)
    detail.value = res.data
    detailVisible.value = true
  } catch (error) {
    console.error('获取详情失败：', error)
  }
}

// 取消分配
const handleCancel = (row) => {
  ElMessageBox.confirm(
    '确认要取消该分配吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await request.post('/app/ky_black/admin/service/assign/cancel', {
        id: row.id
      })
      ElMessage.success('取消分配成功')
      getList()
    } catch (error) {
      console.error('取消分配失败：', error)
    }
  }).catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const data = {
          ...form,
          work_time: workTime.value
        }
        if (dialogType.value === 'add') {
          await request.post('/app/ky_black/admin/service/assign', data)
          ElMessage.success('添加成功')
        } else {
          await request.put(`/app/ky_black/admin/service/assign/${form.id}`, data)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('提交失败：', error)
      }
    }
  })
}

// 初始化
onMounted(() => {
  getOptions()
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .search-wrapper {
    margin-bottom: 20px;
  }
  
  .table-wrapper {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.mx-2 {
  margin: 0 8px;
}

.option-info {
  margin-left: 8px;
  font-size: 12px;
  color: #999;
}
</style> 